package com.base.test.mysql2es.config;

import com.base.test.mysql2es.model.Config;
import com.base.test.mysql2es.util.CollectionUtil;
import com.base.test.mysql2es.util.ObjectUtil;
import lombok.AllArgsConstructor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
@EnableAsync
@AllArgsConstructor
public class TaskConfig implements AsyncConfigurer {

    private final Config config;

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        if (ObjectUtil.isNotBlank(config) && CollectionUtil.isNotEmpty(config.getRelation())) {
            int size = config.getRelation().size() << 2;
            executor.setCorePoolSize(size);
            executor.setMaxPoolSize(size);
            executor.setQueueCapacity(0);
        } else {
            int size = ObjectUtil.PROCESSORS;
            executor.setCorePoolSize(size);
            executor.setMaxPoolSize(size << 2);
            executor.setQueueCapacity(size);
        }

        executor.setThreadNamePrefix("db2es-executor-");
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }
}
